﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Threading;
using Newtonsoft.Json;
using ControllerClient.Bean;

namespace ControllerClient
{
    class socketClient
    {

        //头部长14字节，原版本为22字节
        static int headLen = 14;
        byte[] headByte = new byte[headLen];
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        int port = 8853;
        Thread receiveThread;
        Socket clientSocket;
        string mstate = "";
        bool flag = false;
        static long byteSizeLen = long.Parse(ConfigHelper.GetAppConfig("ByteSize"));
        private static byte[] result = new byte[byteSizeLen];
        public delegate void MyInvoke();
        //硬件初始化
        public delegate void HardwareInitializeHandler(string data);
        public static event HardwareInitializeHandler HardwareInitializeEvent;
        //错误反馈
        public delegate void ErrorFeedbackHandler(string data);
        public static event ErrorFeedbackHandler ErrorFeedbackEvent;
        //电源管理
        public delegate void PowerManagerHandler(string data);
        public static event PowerManagerHandler PowerManagerEvent;
        //数据交换
        public delegate void APDUHandler(string data);
        public static event APDUHandler APDUHandlerEvent;
        //检查环境
        public delegate void CheckEnvironmentHandler(string data);
        public static event CheckEnvironmentHandler CheckEnvironmentEvent;
        //接入
        public delegate void JoinUpHandler(string data);
        public static event JoinUpHandler JoinUpEvent;
       
        //元数据同步
        public delegate void UserDataSyncHandler(string data);
        public static event UserDataSyncHandler UserDataSyncEvent;
        //下发
        public delegate void DownCommondHandler(string data);
        public static event DownCommondHandler DownCommondEvent;
        //执行
        public delegate void ExecuteHandler(string data);
        public static event ExecuteHandler ExecuteEvent;
        //确认
        public delegate void ConfirmHandler(string data);
        public static event ConfirmHandler ConfirmEvent;
        //授权进出安全区域
        public delegate void AuthorizedAccessHandler(byte[] data);
        public static event AuthorizedAccessHandler AuthorizedAccessEvent;
        //static TXTHelper ltCPDU = new TXTHelper("CPDU");
        //static TXTHelper ltMJSequence = new TXTHelper("MJSequence");
        static TXTHelper ltdata = new TXTHelper("data");
        static TXTHelper ltskey = new TXTHelper("skey");
        static TXTHelper ltmkey = new TXTHelper("mkey");
        static TXTHelper lttype = new TXTHelper("decryptType");
        TXTHelper dataMaker = null;
        //private static String response = String.Empty;

        public socketClient(IPAddress mip, int mport,string state)
        {
            mstate = state;
            ip = mip;
            port = mport;
        }
        public bool conn()
        {

            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(new IPEndPoint(ip, port));
                
                LogHelper.Debug("服务器连接成功");
                receiveThread = new Thread(ReceiveMessage);
                
                receiveThread.IsBackground=true;
                receiveThread.Start(clientSocket);
                return true;
                //实现异步接受消息的方法 客户端不断监听消息
                //clientSocket.BeginReceive(result, 0, result.Length, SocketFlags.None, new AsyncCallback(ReceiveMessageAsynchronous), clientSocket);
            }
            catch (Exception e)
            {
                LogHelper.Debug("socket连接中断" + e);
                return false;
                

            }
        }
        public void ReceiveMessageAsynchronous(IAsyncResult clientSocket)
        {
            try
            {
                var socket = clientSocket.AsyncState as Socket;
                socket.BeginReceive(result, 0, result.Length, SocketFlags.None, new AsyncCallback(ReceiveMessageAsynchronous), clientSocket);

                if (socket != null)
                {
                    var length = socket.EndReceive(clientSocket);
                    byte[] test = new byte[length];
                    Array.Copy(result, test, length);
                    LogHelper.Debug("收到异步数据" + HexUtils.byteToHexStr(test));

                }

                //接收下一个消息
                if (socket != null)
                {
                    socket.BeginReceive(result, 0, result.Length, SocketFlags.None, new AsyncCallback(ReceiveMessageAsynchronous), socket);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Debug("ex" + ex);
            }
        }
        public void soekctClose()
        {
            try
            {
                flag = false;
                //clientSocket.Close();
            }
            catch (Exception e)
            {
                LogHelper.Debug("soekctClose出错" + e);
            }
            
        } 
        public void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket;
            myClientSocket = (Socket)clientSocket;
            try
            {
               

               
                
                 StringBuilder sb = new StringBuilder();
                StoreMess sm = new StoreMess();
                flag = true;
                while (flag&& myClientSocket.Connected)
                {

                    
                    int receiveNumber = 0;
                    
                    receiveNumber = myClientSocket.Receive(result, result.Length, 0);
                    
                    if (receiveNumber > 0)
                    {

                        byte[] test = new byte[receiveNumber];
                        Array.Copy(result, test, receiveNumber);
                       
                        sb.Append(HexUtils.byteToHexStr(test));
                      
                        LogicHead lh = HeadHelper.analysisData(HexUtils.strToHexByte(sb.ToString()));


                        ////function编号

                        string length = HexUtils.byteToHexStr(lh.length);
                      
                        string lengthBin = HexUtils.HexStringToBinString(length);
                        int bodyLen = Convert.ToInt32(lengthBin.Substring(4).Replace(" ", ""), 2);
                       
                        if (sb.Length / 2 >= headLen + bodyLen)
                        {
                            while (sb.Length > 0)
                            {
                                string dataMess = sb.ToString();
                                dataMess=dataMess.Substring(0, (headLen + bodyLen) * 2);
                                sb.Remove(0, (headLen + bodyLen) * 2);
                                lh = HeadHelper.analysisData(HexUtils.strToHexByte(dataMess));
                                LogHelper.Debug("下发" + lh.toString());
                                string transport = HexUtils.byteToHexStr(lh.transport);
                                string sequence = HexUtils.byteToHexStr(lh.sequence);



                                //封包指示器
                                string encryIndicate = lengthBin.Substring(2, 2);
                                //payloads是否封包
                                string enceyOrNot = lengthBin.Substring(1, 1);
                                LogHelper.Debug("下发transport" + transport);
                                switch (encryIndicate)
                                {
                                    case( "00"):
                                        LogHelper.Debug("封包指示器:必须不封包" );
                                        break;
                                    case ("11"):
                                        LogHelper.Debug("封包指示器:必须封包");
                                        break;
                                    case ("01"):
                                        LogHelper.Debug("封包指示器:可以封包");
                                        break;
                                    case ("10"):
                                        LogHelper.Debug("封包指示器:可以不封包");
                                        break;
                                }
                                switch (enceyOrNot)
                                {
                                    case ("1"):
                                        LogHelper.Debug("playloads已封包");
                                        break;
                                    case ("0"):
                                        LogHelper.Debug("playloads未封包");
                                        break;
                                }
                                

                                try
                                {


                                       //ltMJSequence.WriteMessage(sequence);
                                    
                                    byte[] payloads = lh.payloads;
                                    string payloadsStr = HexUtils.byteToHexStr(payloads);
                                    if (enceyOrNot.Equals("1"))
                                    {
                                        string skey = ltskey.ReadMessage();
                                       
                                        string type = lttype.ReadMessage();
                                        /*if (type.Equals("02")) 
                                        {
                                            string mkey = ltmkey.ReadMessage();
                                            LogHelper.Debug("mkey" + mkey);
                                            LogHelper.Debug("解包前mac" + payloadsStr.Substring(payloadsStr.Length - 8, 8));
                                            byte[] mac = DESHelper.Decrypt3Des(payloadsStr.Substring(payloadsStr.Length - 8, 8), mkey);
                                            LogHelper.Debug("解包后mac" + HexUtils.byteToHexStr(mac));
                                        }*/
                                        LogHelper.Debug("skey" + skey);
                                        LogHelper.Debug("解包前" + payloadsStr.Substring(0, payloadsStr.Length - 8));
                                        payloads = DESHelper.Decrypt3Des(payloadsStr.Substring(0, payloadsStr.Length - 8), skey);
                                        payloadsStr = HexUtils.byteToHexStr(payloads);
                                        LogHelper.Debug("解包payloads为" + payloadsStr);
                                        //string testStr = "1C3A0DB7790F8B5B8F632AD7644955B81ACBB1E1E92FDBC6D3DBAF7FC75CB3D9912215EB26061432B19868B77282D4CC35DD75B80901BCC142703D7D809759CB5A6314CC7B2749E4F9D112C8E62F6B1CAC5491A3F309C7B19AB687C8A99A71429B2F3B9F3C1D1FF8AF6D751E7BFAC43A1625212E48CC00D163CDBE866A9623B27D8656657D85E5317E6332AA3181D8610A864C7DA054E3AD25D432C046CF626C24CCBF108ABBBF1CD36743DCEC92463E1F703FD63E374DF041C7DFE4666ADDFDA47AE21E91AF99084A398D522711FC6CB69A5AAA2BE23E70E4016A6571B8A43783CC6E32033A6FB3DA31379E27A88C5891874B2F3F1C4132942A7936909B87B44CD102195F3CC5B71BCBC1D010F2C70E247744A664B59097EE54731317BFC2CB6E68D09917E1CA98C781F8F07561D7DFEB2E6A9DE5351B82CAF2B70C7696512E112CA92762A86DAABBC77B0ABE0337D86EDB6E76C5D813F02FDA0978B38A8640A7C86FA6D395A8629CA57D7978AC063F6E7B83D06B509292E6C997B31E87220CADBF644F93F41AB8A44C7D6D4CC6FE32485FEDB560E9BC3930A6D778D820CBDBD93477209E9D1E17013048FE7EAFFA5E8D7A87BE48627B36A951A8E93ED3524F6B1F0FAF2277EF0E5A54671CD9DA8884D2BE88FDA83B92901F839E5706584DDF98C7532BFC4B31F915AE36711695278E49A905B6F21B8E65BA746B184D4B190917C4EB5AC3017E5E47F745830E415315077D7E92A47D24D9F05FEE33DEB735D4A5CF1F77B07E8AB381531F43ADE7B32C145AB5F81C711E439E2B5213B33E41483D3265FD8790F20460FED2C47AF2A5351D56F015EA9A4A7EA10B2C0ECAB4B01CC5428F9DC48E19286C18A1855A9F2E738719B58F46EDF6C9E91E70E410669B26C1A40DA2F08220DBA1815140507A38E9389776FCEDA451BF083DAB172B6FC4F49A12CB082269D53F61B0D7A9442B04B184269E222F8353E019A7BB22ECEAC21671DF7DDC3371226DA7076D965B6D12F743F941EF4B9EF97FA779A0406EB1320EFDB5911BDF5ECDDA920ECE7CBB2FE83BB40A15F102E8CA86E381C3982F29FE4EB3B5F1050440220EE428F799EE6A5454D38ACBADAAFFD4EC29046DB0A501C2A415AA7D097695F753A256FF8DD420DC2DB70731F901B9B5EF171F871FCAD02F645A30AFCA3AD475AD760383F5F379D712E26D2DB39A63C7953BC0B5805CF93E64CE24E466564ECB0B9B93486CDC8006D267C6A49B12F09023FD30502AE7584370CFB62834D9CD25093020E0626505E641D0435387F6717B4DCE0A1BA70C842A96B427032F3EF1951F524DF8C3C0347C5414885DD63E7BB3455AC27FA0A8EAE7D5F925EAE673CF9CB336B50B727A32E0A0A1BFD66BCA13558C876DBC67B019C9D3A3DC83F9C15100CB7D5B6C175E4F4ED4BD0B0F243615AC20AD674C971C4E50F7777DDF358A1ADE0A34843993E8B2B9543A9F520947D5D5EF41D97327341A2BA84647E3617AA9937615D0A9847ED8ACA5D0DEE01475F7CD7F1712DA51E0D6FC3348F623FD2F1CF4831EE56E4AC809FF9517A3133E439E4B1098D9154ED407694BB41866E7FBD57602004660A368A47BF97B06BA1B3858496902FB0553C1E7ED776962169158A4A1B6D1896EC274BF18AAAD88FCF2BFF51F868A0D9D776948BB2A973187E46C830CE904DA3E0EA03EABCEB1121E138332CAC4D9967C29608E2D02CEDC477F9BD9668CD267CFEC793EFF341185724F34B3884E8807947F3DD78FE9811DF0A2DF369C6C9D5A9A690135435E469F6F9B263F57CB120B2A066AF6B20A4C48DF64D23A0396F07424026B7B03A1070EB529137B0ECFDDFF9CC9E6CC27C5355899C709F5FF6D098E3B7A1A4A79B294A8B4EC29C23C6198B57C475853F9489553F7777E0CAEC3F90CECE70FB13AC42DCC45750938ED46813086AC1300C932E8CC559A5D4D3C873E7CA9649DD1FB9C61BD3D0F151413E16C9D2A77B998F0D492E8917323A48E104DB46FB6ED1CEDA25D5877385459311159F13394EB6EE5AE72EADB5233D16A157438B4E8D8928B02331E9AAA53932AA619A332A790C10E4C917FE98E925175EB3FBE30BC1B275F804C85A68C4D10FE8ED95A75E88ED738D9284C95A12C1A13B454C7704E6C9CBE8039E1B8B18FD9B4355F43426E7DEEE2B6418574D8FC28AC24660D6C4F558BDAA82E0C80AC365D0B5A78F403FA1E95461076C93C221C9D5360AD1EDEFC5056A3EFE222DD463D1418B67FE2804122E82781280E410F870E1E56999809CE93AC833800BE509F3E0FA9421B8DD3EDAF41735F36E31618BC220D1B9F46D0BC31AB8D839EEF77822DE67BD61EB5AB3B122FB45DB59884347792E7A3004FEFEBCE56F4D57A93BCF2DCD2B8233D4F4A7C3EC96B931272D04841669BFC9F2C5CE309A8FD91C5E896D17A2A5DBDC42E33E86ECCE9770B5EB9AE2651221EE866B21BAEC8786422AE343AA3C00E5608BDBC1442B678686BBF1D0A5D5D3445B511B80550BB32DF239177521675AC0CE7E1C6A66FFDC67F953CC87DCB6CC854C6DCCB4C5679B705C54FC4A8598F62A84B56415E5068DFAA03AE86F2475B3FBC7DA29B52CF83224CCD414B425BFA28571E94B60AEC51EEF2578E2DD9171BE10DAEEAC20FE3634F000392A40E117B1DF1EF48C010DDE662AAE1E1D49AE2F0F13ABA528009E4DCAAE6A62EA4B469E7BCDB33AA16B48BFDA56135630C7C1796E6B06353EC17C0692329F4CE75F6F1D5C036EE1BECCE62DBDD5449D6536811BAC3386EEE6B0AEF512CB244CA868407E0DF00A1AD2DC0B4D4C7498C6D7BC704A57F85DA2ED0868E82B23AC174435FE93ADC2902FD317EDA0E5C88C29854BDF9ACDCD5648A40CC2BFE2EFBCFE29AD6500F14C7FD6AC287B3070C06DE2F53C646D2660523D6A60557B811C14A2A88742F4EF04226C71CE8E2D5EC98E5798825369B50A688B61CB5AA98650B613DD4B25A62E53C6E813A22B11B6A2302D2F4973CEF2CA6476D637B81A48497F44E6B6167EDB1B582D94A7E859523A6DD08C3AFF2DBCAD6C6124AE72EF82877D3E3BA2A4EF3D616B34AF522545BC35089538D671BB4EFD510B221AB628815A4F6DCA5D6FE588ACBA5B154CA496ABAF48F236C6242190C99DB23FF2E719401A59F7E38FAE3AADCACC8F1BEAC4F0B5D5AAC11A68F796631CF81E743E10F153C8ED1981756497F6979C4DBE3DF0C7E1AB981F4ECCDD04A1C872316091BB1B28601C13CBB59DBA3B6EC66D8FB58256EBA07543C741C26CA531BD21FD3F657D9AD7426F08E08A5A0CC334D12EFE27E5E1865907591E1AF6D556890A48596691FE17C95AF64AE62A0E9918FFEB2571E5E420647D2DF5010F392C5192A94C45E3B781DE1312A8938F8BDC3563136FB0D125F7A02C36F350CCA6BEDC382CD460824E410F087AF4197A719F3ADF2117F8963CF21A4DEBE70E9C3EC046CCF3F4ECAAFF2E604718168289546D1C87BB7661EF5FDDE36085777A376F0407D264BC65AC321A188949D05760665FF2D9368EDE697361AF999D045B96F04FB12B4DB15A61DD4DF70E41FCCAB30A4F6E7ADD106AEB005A548F6D1354F2FAC38198F0FC9F8CC74C2071847913A99550A6A794D63C4987D1DC2292E5A4A8F0EE4745976BA4CFACD7595B13CB59453DF11506B2DE3538AB57939267A4CC8A0133C7DF2CD11D97A07C2AF1D6E92BAA3ADF53005C245A28036DD1A9946CB4D43290FD206F8136D4FAF6384DFE50CFEC3F9C7BEB46BD589829D8C64BF7214A6B312A167B224B8838174BF3BFBBD1BA88C4EF90537B1123B51ACCA49846B545C4EF115E9CCEA2075C5DE93C65836A45DB21492845B1E5EE91FF0D2791C48D496D690ED907AF699113066EE5B0DAADC650104B896F4069F0F4B7B81F174909C835965601133FAC7D48EE06D4F2741AD6A2169B04C1ACFC068C3B889467734721D42D613C5BD6AE81B9B214E8627CFE3A5DE4C7342204A2298D1D922EB716D28D0B57707F4756F823AAF1DBBCF629AAC3BA71B6C86F8BD8E4EFC2BA620FCF7915C9E3C57C6DE2CBBB881E3BD8E582B71C8AFCE7B9E7497FC23D6A3B6EB3437F95BF5920C5F7E97FC012C4345268F4943E849DE6FBD8D92EFC32AAED35661AB2CBB8A2AD7D2925CF967D8C7B4BD15201CAD75353982D06849BDD53DF7F5DD5EEF97B40F53A6FFC294CAE295367CB7BDE614652DA3518A112B937FDE41AF453D3E71F4E0C02D7BE0E62391DD95C746BC99E5CE160C3C773769C4FE7B6E9B59B2E083FC0ABF8FCC49908FC17FDBF171DF8761E9D4F65914F77BD8F03EFF0A6C58E598B017D3C5F2AFD8F01ADC01FCE8217B209DA8A0903F96B462072F009FCCA56968CEFC80640053E61349A43ACE3C65DEC00E14A84D85A3C7DD141BA086193F59E09E1F742DE93940FA8CACBB99946135B1AB48D624B7BD1CDD556483781C908C78F3FB1CD77B7AC892D7F77ED2BD0FA8EA152C0956DC2F6489DF69978AE0583998BB7338BDC9A8144DE3D1A2AF9ADD8952B2B8B794CD6A963D8DA7FEE25FAAE8C193F7D803C9819B38F621A139FF3E218E5CB99C2F83B8F2FE42E244B19EA7189814318D4D897C06C3ED736671FA8ED0BAD27FFAE693AB431ED7F8494B47F4A8827009DA0045D289DC49AADA8CD83F1B5086A3DCBD30B4008EF96E28715DAA99E11BD1D535A8E7559976BB64D156912ABBF110F84F0D8A323839BF9C8923E91F143A48E6364F20980D8E4D3B8E9430F2E4C4C6613D201684DFAE19AA07A906F8C9B77DC113BE7FD820A926CE5CD561C0A17BCA9799171CCF81D19F42629C0070D58EB120C450C5CA90828AF93D0B7F08386F0C7C7A6308F32D34CF125765A4CA0E14BD4290466D167EB3B51F433E05A9513B4C60C3092E9922D1FCDBEDCBCF6D97D98C01F07BF2A674E26341DDE122D745FB020AB5396EB9E0E6CEEE7C64D73388B91F8944E1B0A957175E24AE0FF5E551A88B39F50152B3151837AEEFCB04FF795AD44A79BF81FEB0F516ECB61AC491B7D28FA6469E8CD9D19DB189CCF8FF92725BC955ABD2B07F884BB97E5A444B171A1CB721931F492B1834DC98E1070BC805D6E6A1AEECB5DC2E2286982CB7E629C9D366B53184A018614BFF6C6FD8B44F3F0227F00F809B303ABDB244555F7F42318A0BD4B561E871055CD6ACD6E695669159718F7B998FF20AED12A1E603149FDC2CE2EFB741540B20E9C76E30588DF37117B3E4705B8F51D84CD1E864843FCD20AB09A124310D80FA2BAFFBA806A6703034247E871EA7EB8A4126B0F60E2F500F6273F945BA9B02D190530231A82100855884BC66492772834E8C30AED528AAF0F08FFE2E772BC86A7FF7A1CA6D3CE4641F2B856DCC3A2249802F6E9A319F0242274C683D74D8DF639736A4027199FFDCF4A0E7785346291A0FFEF7A7E7DFBEB331EB31BD892FD1233871E308F960A3B773ACCB36641A9AB4C5C60B0498BC08BBAC253700B8C864F90CD2942E01261E7D7B940603E2C10526E7FCB91F1F9A9A85BBCB05E16C584D4FDE439287B925D78E7366163D25753B87BEC10AE97EFE93D8D5083DFC4192CE8CB7C44768D124420B4066F9B7220143CAEDC8D88E9D3C02B0F9DBAD4B977005C7556C48C01ED6050DA146ABECE0038A05714F1A3379070E99013CB5BF79FAF2FF819417B68835912BFE525DAE424DD881E6FEB04E59B76C4BB3541F59623338AA5B12E17BEB85E6DDC7DD137BCDA69CFBBEE272B6799824863D806E1B5396520C0EEE9A6860BBAB030E3FE0FB55D088A156A9CBFC97A46C8138AF1CC5B4DF1ED8FCFAE0EE45CFFBF0F05328B14E784986F6537FCF5F2E8E3B37EE67B50337A521DD02CF83A4AF131CD1F2B586856BB6D1DD7A1412FEE3B1A717DE957443E0791AF1938421D98CC5B37C656C952D78C20CFFDC63096C95E7D858FC4064775876A613882AD4885BCF5EACF675139EE7D53CE47F2415AFE18F587954F6DCF994FDD9EBCAF5D06AE3B3C0452C67466F57214853972CE529EA21FD45DB22D23E61764AC27DF390C791F1A8F2664C5A211602F8E7C9DA2556CFD77922D588E3D64C2461C9ADD4CF079B6256B6EF8B404B024D2C85AB92FB92712666679F6BEBEFAE7D9CC6652739D6C8FD60A4BA410FAC00B87FD658B6C6364661C71D60BE0445366989D7D155865618B8B25373FA6A7CF497B47C1AF673DC0943902D2FE91E5F9073F15A40613D2FD9D0F2D68896E978554D5C1F21EB1B08ABC70908EFA08CDCA3E97D4D5B284978C0F0AD6212625A27ECABFB87FB755AE8BBBA664A39D2DC807F3E17967AEAD827099E0708A06DB81805BD1C7B0B7C4615F1ED8198E1F3AAFD8B73639CC65A359520C3B7E190CE72164DCD12C933037CA8B2EFE60283E7B8989E0BC6B47A6D50188576322B9362B2E1AEAB47A2183499BE4DE418F803C7844C20417F5A82ECF94AAED1DE5850063D25401007162B6E646B60715AB0B76F0088ED083FF3E83BB2B984AE160BFADB61AE2451A413F290251C4B2A39F1EA0FAF320ADF7F8E49184759AC4982EACEC202DD47D8762257B1F096763ACE6E7AF5FA58D3A0931F39E8CD901BA1F9634EF427C26A49DD7AEB57899C0A772EA485FFE58BC7EC9241AC91007A45A98A8DA17814B2E5C8FC38EE61499EDEC59DB9786971B1213FAA15E4B8F0564E9A76D1C4AF461A28E2FD40F1A82083B974709A07092E3D64E0344EF04C5254DB01290A64F5EDD0EAADF33A61E85BD3E4BB682F22076469941D8FAFD24D7FD00B4F8E1EB137252CB30431966A3BB10F19F7CB2BEA08AC6D37BBFEDC267A6F2FA989E3F3A7C88BD7A6490E17773D2F179702520597756BBC06BD9B2298D33B2F1EBE4CC7EC2ED296A8EDF8B45587E64F5CFF4BBAEA864D108F8A4D45730D9F34183BD64022CC4C941626B28956CFF68CDE1C241D904EE56A86476A32F808C911BBD4D69C3FD39E5B8DA7AEE43E9397670A2A37B205B367556104E00D1FEC73D54E7FE4B2BAB26A2A7D2A00514B8029F848956869A5FC003FC37676F9412C21D75F7BD761C655C0EF0739378E119E7CF93690CDB626C2120AA161F1BB90268485997B7CD26068491DEC98DCF1A4D6F9FE1AD0EA06EA0AAC7B9523922198AF9953BDA1861A2E8D7AAA9C1601AF6A7866CF415F87CE3ED9E0888081F0320034EB73460997DC83E87A1A272D57368AE47F7609CA22C89643928E1AC5354CE53D47B37FBE239968E456B5F3706D435C00513AEF37818385082AEB557466C782F6C5734FCBAF08F0162ABDE22437537113CFE87FE7FEC6B11C16CCE1A7CB45753A681EEA7730E1D8ACC6BC07B57365971A96C210A83565C13D34BD2F1F638F096DE6EA2D32AEAECA2E5EE942F09766A9411E487CB358637DC8F45C0260241D675B5A4095B26595E8E6B6326651EBE350D6F0894CE2CD916D8CE0BB4036722A56AEE76A36AB7D05B54C26301DC6EDD95A42FAC3560B3985D2FB24D086B51B6362328BCBC29657C18B287CC324287DCC2690555AE6B421CC5EF072AEBE0C2E58E9AC1A8C64DCEC87900ECCDFB962B4A63A06C54365A0ABBA45E14846EDB20A209B29D12EF58A041F92764381B5FB60591C2622F2BC19C1EC002114E2A789E303A158BD8D9106DCA60C4B03023D53F3BC833FF2C694FF54303819C196BA144A3DF3D2D02F2C38C6FFA6932CDEE8D6D7238EA401ACC250EF277FF2C4CEF39760170CD6FEFD2FB7F6B303D35675433300BDFBF6418CA832F4CB1F6109A484ACB19C1C3D64597F353D1E4E1FFB7DBECB0FE11BF295823CA92365F90E37F1D0C0791EF21BAA5D1423666F09CED1E045A887C72E780F3874E0DFD82F89A736FC1DDE89861E3C9F1F8118644DDB9EA9A1D17DE7BB28486DEA00763983B3151DCB7338FB01354D06EB1D5E95B4D6821B11850742C27714F4D8BEA46F24746CDD73363949A3CBBFD1DE4AF5A9AEED6D6176EC90E41A2EE64384536BDF9460076C5EEE8B0D65C2E906B604436250306D1B430157F09A1954A5267A343CD802027D86A6EEA44FF21CA21B46048320DE0989024284F20735FD7DA3EBD0EFA5D2E1D4F99D74C433A7ED503CC7CCB0EC4CFC57A157764129EBB62EAC38B408BE867EF7A93E806B7CB976F6BD2B43C5CC3E072FCB9214028F8A0D49928149840E3BF5F7B9C3402784A855820984F2A71136A769DC0B469F5A28AFB0A5C03DDBB60D8DBB4BBD3BF8C69280802C1910CA104A46D3317C4860E96A1BF839E102CBF902B98023AA94C1286B8A0322F320F7E234DD90DD2C091E2436626AB9223742003511A56C11ADF42267AC230972439AD3A53AC946D55347F392A2390BEF210ADA3B301A638856AF1CED850D80B1DCC8F8DA0006B4831774952EE47331C4843FBCAEEC3579355ECB9826F84AF6724A9961CC3729B3D800C0C9F9AC5964A12BA91D08900004F4AE9C6D0368B6F34816B26A43805180E6A3683A070BFFC07550D3A16F82D9BBD170F5620F84B43B03B0417C4F9521C27BC8A6088330D8C7C15DE7F186F2EE448E547BDAC92884188EDC90B08C45E5FD34924809B18B37D24E10F60C5C241ED227DB80B7AB8D5609D8A06307106F299FEDC7BCE8AD159C928ACEB92A36FF7D62E5756F7E994EAA5E0F4D1F57E79B1119F2C413A06B45FA29B3B1F20B397A15AD2B0F0183B6D6CC865CC725BD21A2DA98E7C475EDAFE7A9EBBD885FFD861617ED36B1C0BD6A3462790148638EB7B2969718A5758E01123F289F3633028FBFEA3509B22AB83FFE36B9EFE653D2C4EEBD976B938B4320591A529484FD790E4AA7C01EF043E5AF4A0E1E2D28596403B00A741A337E50D5849A2C84FAE294B8B26EF879D06DF51326DE57C50BA059E342403AD4833809FDF239F0E14268AA52BBCE8D741A57CFB6BE9F56A48BA9C454DF3EB017434096727E06300C361F6C139B6452189180C0A76AD581B7A4E9131F3A3341BEC7D38B7463B818AA542CCF5D4C7FD8BF3BC5E4A7D0DFFA9C6EB538F4797C939E4B1346EEF91CBDD13DAD5A11A865429A69361E3F00C7C6A9F3167FA08046A7D33B699AF5C42B497AD1D6253B03023E77835504673E51AD59E7DEFE328A42FE5AA9D16531D44940C6E5484D4EE595C0ECF6BDBF7F30F66F10DB968EE9CAB5C97049D16C0F1E08AC6CB25AF5311D12B62C22D069A67640F675720E4492093CA630DA7AEBF2B886B46559103F2F06B1E1817B52DC9ACD98BAFC17943C818A6245E56A38FA21BA0278B571447D082A50C87C8E031AF8BF4A72DFBF3EAF0C8B385A39231B6FAFFF01B6B2E3B73BC935083F5F1759E1867A81493BFAE33FFFE9CCBB8B6DAD86BFB4D81EB9498A453175F19A2714BBE222B9A4C8D71C6D1D1F3F2C4AD1CC73100FDD1B39A4522F44118695C220C2F9C94A6D24A6A70B8072A5BC11F685E3D87CF8005F1449378B7D1563D5E8EAA1BFD0591F5C7C6C55D082202C709FD115875DFD6B09DE8004FE1F134BC9E889FAEAD6A73FB8A627506EE6DDF88CFD77BA2F3DCAF06857563B63898E3F12E0E7F8A4EBB3E05E53E89BBC61DBFCA89423B3254C7923EC6C72E63044BBF604109929449130994BD1F18B6E73950CC1D1A7AE949DF71243FDDB8957D8D3B5421526E5263C9B85F7C95AA0935A35ED602D569B63773CB0EAC5BE4AB0833FD7345C88BC479FE1EC9E27DA04A764E5E5516A9EF42FB046976130833E436BB36CDD3417073DD09671976B153B21D09171CB70A57F853009A13A27C2F4516C1567BD1A5F2F9A42351D34D02FF6BF229C7A5C4E60155B14D7CD2559648F54D2CF949EA5441EBC7CE97CD00EE1AF75DEA0E1B91F8B1E05AA5252E7F929B539980ACF8532B2F0DF2AC1900A4D94BB33B3FCB31BCA138CD11F0B7B40BDE19919C9966600C95F330CA5800E029EAB24B03B8C25E30BE34A6DE874BA2B3272D95A39BEB70FB5FBCFEBDA5A82BBF306FABC90ADF2845A1BBE1FDD7A8324D1FF58A9D77E34A3B3F1BD1C458414DE125EAE7A88CF8968BD24CED827234C62ADCB5A85D6D9583673AE6333F2CCFAD85819DAEAB1D2E5D8A577BC7FA222AB67298048206B4D555B836A4719FEF1F1D53F37E41ECAFC65E8631311A1281F09C9D4B0D86A522B9254DD2EA3CB3C1C71CF2424F4FF1B2D5FD9CEA3A8FB27747466E7C790AB02F7ECD777A16036E1A69EBFD1CB2477139D237E3B14C6B6F4C99FA34AC491C241FE3CC17D7E626BD4F1182DD9BFFC304CE9D4FC1BA3028E1194FE82AEDE57987EC2AB4E686D362996AF7A4EF384095E0D1779E0C69A54DB7C04D917C44536BA14AD8AA9EC698F874C72B9E944B621CAE83C49A5403D02309344AC69C4C806540DF0731FD25A64FDB702B2DDC3C05F379B9E3DB0781B28AA3D2314F327395F42A3EDB65AA095AFD17BF6C2F5F2305426C771A52E8005E489C133760996BE989F868B430F1CC4F1132836E84A2EA9C4C63ECE9A3A9CCC86E6B08F1C3938837D12EF0C44E8321D2F42AD81F624B5811B30D5380FB30844C309D39A68AF7E450064F42A5BC7CB932B157D3538EC68F93070EE6ED16DC54D5CC3C868C705D12825FD8FB001DA20B16F94CF74D80D68B48B0894ED991025B9DA0DFD4B742E45B4E6BBEF941A8A3F5039D26645FD8317A28D5CDE7BAFC500289CBE936410669EE84E5BE33D87013BC7292ADD02EEDF7C303D3FBF2497C19072AB52B6ED8E4FE9F3D23C396692A6F2F2F5578851";
                                        //string testSkey = "31A126E0CD9D69A5A0789D05D10513B1";
                                        //LogHelper.Debug("testSkey" + HexUtils.byteToHexStr(DESHelper.Decrypt3Des(testStr, testSkey)));
                                        //string payloadsTest = HexUtils.byteToHexStr(DESHelper.Decrypt3Des(testStr, testSkey));
                                        //int metadataLen = Convert.ToInt32(payloadsTest.Substring(0, 8), 16) * 2;
                                        //string call = payloadsTest.Substring(8, metadataLen);
                                        //LogHelper.Debug("callTest" + Encoding.UTF8.GetString(HexUtils.strToHexByte(call)));

                                    }
                                    if (transport.Equals("1001"))
                                    {
                                        string version = Encoding.UTF8.GetString(payloads.Skip(4).ToArray());
                                      
                                        LogHelper.Debug("version" + version);

                                        if (HardwareInitializeEvent != null)
                                        {
                                            HardwareInitializeEvent(version + ":" + mstate);
                                        }
                                    }
                                    else if (transport.Equals("1002"))
                                    {

                                        string data = sequence + ":" + payloadsStr + ":" + mstate;
                                        if (ErrorFeedbackEvent != null)
                                        {
                                            ErrorFeedbackEvent(data);
                                        }
                                    }
                                    else if (transport.Equals("8001"))
                                    {
                                        string data = sequence + ":" + payloadsStr + ":" + encryIndicate + ":" + enceyOrNot + ":" + mstate;
                                        //LogHelper.Debug("data" + data);
                                        if (PowerManagerEvent != null)
                                        {
                                            PowerManagerEvent(data);
                                        }

                                    }
                                    else if (transport.Equals("8002"))
                                    {
                                        byte[] apduLen = new byte[4];

                                        Array.Copy(payloads, 2, apduLen, 0, 4);
                                        int apduToInt = HexUtils.ToInt(apduLen);

                                        byte[] apdu = new byte[apduToInt];
                                        Array.Copy(payloads, 6, apdu, 0, apduToInt);
                                        byte[] rh = new byte[2];
                                        byte[] ch = new byte[2];
                                        Array.Copy(payloads, 0, ch, 0, 2);
                                        Array.Copy(payloads, 6 + apduToInt, rh, 0, 2);

                                       LogHelper.Debug("接收C-handler" + HexUtils.byteToHexStr(ch));
                                       LogHelper.Debug("接收apdu" + HexUtils.byteToHexStr(apdu));
                                       LogHelper.Debug("接收R-handler" + HexUtils.byteToHexStr(rh));
                                        string mess = HexUtils.byteToHexStr(apdu) + HexUtils.byteToHexStr(rh) + HexUtils.byteToHexStr(ch);
                                        //ltCPDU.WriteMessage(mess);
                                        string data = sequence + ":" + mess + ":" + encryIndicate + ":" + enceyOrNot + ":" + mstate;

                                        if (APDUHandlerEvent != null)
                                        {
                                            APDUHandlerEvent(data);
                                        }

                                    }
                                    else if (transport.Equals("1004"))
                                    {
                                        string data = sequence + ":" + payloadsStr + ":" + mstate+":"+ encryIndicate;
                                        if (CheckEnvironmentEvent != null)
                                        {
                                            CheckEnvironmentEvent(data);
                                        }
                                    }

                                    else if (transport.Equals("1005"))
                                    {

                                        byte[] datetime = payloads.Skip(1).Take(8).ToArray();
                                        string datetimeStr = HexUtils.byteToHexStr(datetime);

                                        string session = payloads[0].ToString();
                                        string data = sequence + ":" + datetimeStr + ":" + session + ":" + mstate+":"+ encryIndicate;
                                        if (JoinUpEvent != null)
                                        {
                                            JoinUpEvent(data);
                                        }
                                    }
                                    else if (transport.Equals("2005"))
                                    {
                                        //元数据同步
                                        string data = sequence + ":" + payloadsStr + ":" + mstate+":"+ encryIndicate;
                                        if (UserDataSyncEvent != null)
                                        {
                                            UserDataSyncEvent(data);
                                        }

                                    }
                                    //下发
                                    else if (transport.Equals("2002"))
                                    {

                                        //string eid = payloadsStr.Substring(0, 4);
                                        string id = payloadsStr.Substring(0, 8);
                                        string datetime = payloadsStr.Substring(8, 16);
                                        //string dataTo = "";
                                        string dataTo = payloadsStr.Substring(24, payloadsStr.Length - 24);
                                        string operatorUser = "0";
                                        string auditoruser = "0";
                                        string data = sequence + ":" + id + ":" + datetime + ":" + dataTo + ":" + encryIndicate + ":" + enceyOrNot + ":" + mstate;

                                        //ltdata.WriteMessage(dataExchangge);
                                        string taskIdBin = HexUtils.HexStringToBinString(id).Replace(" ", "");
                                        LogHelper.Debug("二进制taskId===" + taskIdBin);
                                        string dataExchangge = id + ":" + datetime + ":" + dataTo + ":" + operatorUser + ":" + auditoruser;

                                        if (taskIdBin.Substring(0, 1).Equals("1"))
                                        {
                                            taskIdBin = "0" + taskIdBin.Substring(1, 31);
                                            Console.WriteLine("===taskIdBin" + taskIdBin);
                                            id = HexUtils.binStringToHexString(taskIdBin);
                                            id = id.PadLeft(8, '0');
                                            dataMaker = new TXTHelper(id + "data");
                                            dataMaker.WriteMessage(dataExchangge);
                                        }


                                        if (DownCommondEvent != null)
                                        {
                                            DownCommondEvent(data);
                                        }

                                        //id中最高位1为脱机数据，0为联机数据

                                       // LogHelper.Debug("id" + id);
                                      

                                    }

                                    //事件
                                    else if (transport.Equals("4001"))
                                    {
                                        if (payloads != null)
                                        {
                                            string error = Encoding.UTF8.GetString(payloads);
                                            LogHelper.Debug("error" + error);
                                        }

                                    }
                                    //执行
                                    else if (transport.Equals("2003"))
                                    {
                                        string id = payloadsStr.Substring(0, 8);

                                        //ltid.WriteMessage(id);

                                        LogHelper.Debug("任务id" + id);
                                        string data = sequence + ":" + id + ":" + encryIndicate + ":" + enceyOrNot + ":" + mstate;
                                        if (ExecuteEvent != null)
                                        {
                                            ExecuteEvent(data);
                                        }
                                    }
                                    //提交
                                    else if (transport.Equals("4002"))
                                    {
                                        string error = Encoding.UTF8.GetString(payloads);
                                        LogHelper.Debug("error" + error);
                                    }
                                    else if (transport.Equals("4003"))
                                    {
                                       
                                        if (AuthorizedAccessEvent != null)
                                        {
                                            AuthorizedAccessEvent(payloads);
                                        }
                                    }
                                    //确认
                                    else if (transport.Equals("2004"))
                                    {
                                        //string eid = payloadsStr.Substring(0, 4);
                                        string id = payloadsStr.Substring(0, 8);
                                        string fragment = payloadsStr.Substring(8, 8);
                                        string complete = payloadsStr.Substring(16, 4);
                                        //string data = sequence + ":" + id + ":" + fragment + ":" + complete + ":" + encryIndicate + ":" + enceyOrNot + ":" + mstate;
                                        string data = sequence + ":" + payloadsStr + ":" + encryIndicate + ":" + mstate;
                                        if (ConfirmEvent != null)
                                        {
                                            ConfirmEvent(data);
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    LogHelper.Debug("命令解析出错" + e);
                                }

                                if (sb.Length > 0)
                                {
                                    LogicHead hh = HeadHelper.analysisData(HexUtils.strToHexByte(sb.ToString()));
                                    transport = HexUtils.byteToHexStr(hh.transport);
                                    sequence = HexUtils.byteToHexStr(hh.sequence);
                                    length = HexUtils.byteToHexStr(hh.length);
                                    lengthBin = HexUtils.HexStringToBinString(length);
                                    bodyLen = Convert.ToInt32(lengthBin.Substring(4).Replace(" ", ""), 2);
                                    LogHelper.Debug("payloads长度====" + bodyLen);
                                }
                                else
                                {
                                    break;
                                }
                               
                            }
                            
                           // sb.Clear();
                        }
                       
                    }
                    
                    else
                    {
                        LogHelper.Debug("当前无报文");
                       break;
                    }

                }
                myClientSocket.Close();
            }
            catch (Exception e)
            {
                myClientSocket.Close();
                LogHelper.Debug("receive出错" + e);
            }
        }
        //同步发送
        public void send(byte[] data)
        {          
            try
            {
                //LogHelper.Debug("发送" +HexUtils.byteToHexStr(data));
                clientSocket.Send(data);

            }
            catch (Exception e)
            {
                LogHelper.Debug("发送error" + e);
            }
        }
        //异步发送
        public void sendAsynchronous(byte[] data)
        {
            try
            {

                clientSocket.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult =>
                {
                    try
                    {
                        //完成消息发送
                        int len = clientSocket.EndSend(asyncResult);
                        LogHelper.Debug("客户端发送长度" + len);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Debug("error ex=" + ex.Message + " " + ex.StackTrace);
                    }
                }, null);


            }
            catch (Exception e)
            {
                LogHelper.Debug("异步发送出错"+e.ToString());
            }
        }
        private void SetText()
        {
            //textBox.Text += str + "\r\n";
            //textBox.SelectionStart = textBox.Text.Length;  //设定光标位置
            //textBox.ScrollToCaret();
        }
        public   bool socketConn()
        {
            return clientSocket.Connected;
        }
    }
}
